package com.dyh.quickdemozwei.futureopreate;


import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;


public  abstract class AbstractFutureOperate implements FutureOperate{

    private static final Object NOT_READY = new Object();

//    enum  DataZone{
//        INPUT,
//        OUTPUT,
//        STATUS
//    }
//    protected Object[] datas={NOT_READY,NOT_READY,NOT_READY};

    private static final AtomicReferenceFieldUpdater<AbstractFutureOperate, Object> OUTPUT_UPDATER =
            AtomicReferenceFieldUpdater.newUpdater(AbstractFutureOperate.class, Object.class, "output");
    private volatile Object output=NOT_READY;

    protected List<FutureOperate> listeners;

    @Override
    public boolean finished() {
        return !NOT_READY.equals(output);
    }

    @Override
    public Object getOutput() {
        return output;
    }

    public void setOutPut(Object obj){
        if (OUTPUT_UPDATER.compareAndSet(this,NOT_READY,obj))
            return;
        throw new IllegalStateException();
    }

    @Override
    public void addListener(FutureOperate operate) {
        if (listeners==null)
            listeners=new ArrayList<>();
        listeners.add(operate);
    }

    @Override
    public void onFinished() {
        if (!CollectionUtils.isEmpty(listeners)){
            for (FutureOperate listener : listeners) {
                listener.work(getOutput());
                listener.onFinished();
            }
        }
    }
}
